/**
 * 资源加载器
 */
define(['async'],function(async){
	var RSLoader = function(){
		
		//常用标识
		this.rsUrl = false;
		this.data = false;
		this.imgObj = false;
		
		//私有变量
		this._recordCount = false;
		this._records = false;
		
		//方法
		/**
		 * 初始化方法
		 */
		this.init = function(rsUrl,callback){
			this.rsUrl = rsUrl;
			async.waterfall([
				//先加载event.json
			    function(callback) {
			    	this.__loadData(function(flag,data){
			    		if(flag){
			    			callback(null,data);
			    		}
			    		else
			    			callback(data);
			    	});
			    }.bind(this),
			    function(data, callback) {
				this.__loadImg(data,function(images){
					this.imgObj = images;
				    	this.data = data;
				    	this._records = data.records;
				    	this._recordCount = this._records.length;
				    	callback(null);

				}.bind(this));

			    	// var images = this.__loadImg(data);
			    	
			    }.bind(this)
			], function (err, result) {
				console.log('资源初始化');
				callback(err);
			}.bind(this));
		}
		
		/**
		 * 得到某一段数据
		 * @param {Float} startTime 开始时间
		 * @param {Float} endTime 结束时间
		 */
		this.getData = function(startTime,endTime){
			console.log("开始时间："+startTime + ",结束时间："+endTime);
			startTime = parseFloat(startTime);
			endTime = parseFloat(endTime);
			var _recordFlag = false;
			var array = [];
			console.log(this._recordCount);
			for(var i=0;i<this._recordCount;i++){
				var timestamp = parseFloat(this._records[i].timestamp);
				if(startTime <= timestamp){
					_recordFlag = true;
					
					//加入isAdd
					if(i > 0){
						var _j = i;
						while(this._records[--_j].isAdd ==  0){
							array.push(this._records[_j]);
						}
					}
				}
				else
					continue;

				if(_recordFlag){
					if(endTime >= timestamp){
						//距离上一个节点的时间间隔，，
//						var timeDiff = 0;
//						if(i>0){
//							var preTimestamp = parseFloat(this._records[i-1].timestamp);
//							if(startTime > preTimestamp)
//								preTimestamp = startTime;
//							timeDiff = timestamp - preTimestamp;
//						}
//						this._records[i].timeDiff = timeDiff;
						array.push(this._records[i]);
					}
					else
						break;
				}
			}
			
			return array;
        }
		
		
		//私有方法
		/**
		 * 加载event.json的方法
		 * @param {Function} callback 回调
		 */
		this.__loadData = function(callback){
			this.__makeRequest(this.rsUrl+"/event.json","",function(flag,data){
				if(flag)
					data = JSON.parse(data);
				callback(flag,data);
			});
		}
		
		/**
		 * 加载image数组的方法
		 * @param {Function} callback 回调 data数据
		 */
		this.__loadImg = function(data,callback){
			var records = data.records;
			var imgobj = null;
			
			var obj = {
				img : {},
				fileOrPpt : {}
			}

			async.each(records, function(record, cb) {

				if(record.timestamp < 0)
			            		record.timestamp = 0;

			            	if(record.class == "DRFileRecord"){//如果是图片 ppt file 类资源
					if(record.fileType == 1){//如果是图片
						if(!obj.img.hasOwnProperty(record.relativeSourcePath)){//并且没有存储上
							imgobj = new Image();
							imgobj.src = this.rsUrl +"/"+ record.relativeSourcePath;
							imgobj.onload = function(event){
								var image = event.target;
								obj.img[record.relativeSourcePath] = image;
								cb();
							}							
						}
					}else{//如果是 ppt 或 文件 type == ppt or file
						if(!obj.fileOrPpt.hasOwnProperty(record.relativeSourcePath)){
							imgobj = new Image();
							imgobj.src = this.rsUrl + record.relativeSourcePath;
							imgobj.onload = function(event){
								var image = event.target;
								image.pageIndex = record.pageIndex;
								obj.fileOrPpt[record.relativeSourcePath] = image;
								cb();
							}
						}
					}
								
				}else
					cb();
			}.bind(this), function(err) {
				if(err)
					console.error('err: ' + err);
				callback(obj);
			}.bind(this));
		
		}
		
		/**
		 * 对网络请求做简单封装（只能是GET请求）
		 * @param {String} url 网络请求路径
		 * @param {String} data 传送的数据，默认形式：name=value&anothername=othervalue&so=on
		 * @param {Function} callback 回调 参数1：请求成功或失败的标识 参数2：数据
		 */
		this.__makeRequest = function(url,data,callback) {
	        var http_request = false;
	        if (window.XMLHttpRequest) { // Mozilla, Safari,...
	            http_request = new XMLHttpRequest();
	            if (http_request.overrideMimeType) {
	                http_request.overrideMimeType('text/xml');
	            }
	        } else if (window.ActiveXObject) { // IE
	            try {
	                http_request = new ActiveXObject("Msxml2.XMLHTTP");
	            } catch (e) {
	                try {
	                    http_request = new ActiveXObject("Microsoft.XMLHTTP");
	                } catch (e) {}
	            }
	        }
	
	        if (!http_request) {
	            console.error('什么破浏览器，ajax都支持不了！！');
	            callback(false,new Error("浏览器不支持AJAX"));
	            return false;
	        }
	        http_request.onreadystatechange = function(){
	        	if (this.readyState == 4) {
		            if (this.status == 200) {
		                callback(true,this.responseText);
		            } else {
		                callback(false,new Error("AJAX请求失败"));
		            }
		        }
	        };
	        http_request.open('GET', url, true);
	        http_request.send(data);
    	}
	};
	return RSLoader;
});